package com.wl.convert;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import static com.wl.common.WindowComponent.showAlert;

public class PdfToDocxConverter {

  public static void convertPdfToDocx(File pdfFile) {
    String pdfPath = pdfFile.getAbsolutePath();
    String docxPath = pdfPath.substring(0, pdfPath.lastIndexOf('.')) + ".docx";

    try (PDDocument pdfDocument = PDDocument.load(pdfFile);
         XWPFDocument docxDocument = new XWPFDocument()) {

      PDFTextStripper pdfStripper = new PDFTextStripper();
      String text = pdfStripper.getText(pdfDocument);

      XWPFParagraph paragraph = docxDocument.createParagraph();
      paragraph.createRun().setText(text);

      try (FileOutputStream out = new FileOutputStream(new File(docxPath))) {
        docxDocument.write(out);
      }

      showAlert("转换成功！", "当前文件已经转换成功请查看。", pdfFile.getName() + "已经成功转换为docx类型");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void convertPdfToDoc(File pdfFile) {
    String pdfPath = pdfFile.getAbsolutePath();
    String docxPath = pdfPath.substring(0, pdfPath.lastIndexOf('.')) + ".doc";

    try (PDDocument pdfDocument = PDDocument.load(pdfFile);
         XWPFDocument docxDocument = new XWPFDocument()) {

      PDFTextStripper pdfStripper = new PDFTextStripper();
      String text = pdfStripper.getText(pdfDocument);

      XWPFParagraph paragraph = docxDocument.createParagraph();
      paragraph.createRun().setText(text);

      try (FileOutputStream out = new FileOutputStream(new File(docxPath))) {
        docxDocument.write(out);
      }

      showAlert("转换成功！", "当前文件已经转换成功请查看。", pdfFile.getName() + "已经成功转换为doc类型");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
